import { _decorator, Component, Node, Prefab, Label, Sprite, SpriteFrame, instantiate, find, director } from 'cc';
import useStore from "../store";
import api from '../api'
const { ccclass, property } = _decorator;

@ccclass('achievementMgr')
export class achievementMgr extends Component {

    @property({ type: Node })
    public goBack: Node | null = null; // 返回

    @property({ type: Prefab })
    public item: Prefab | null = null; // item  item-Prefab

    @property({ type: [SpriteFrame] })
    public statusList: SpriteFrame[] = [] // 状态

    @property({ type: [SpriteFrame] })
    public defaultGZList: SpriteFrame[] = [] // 默认官职list

    @property({ type: [SpriteFrame] })
    public activeGZList: SpriteFrame[] = []  // 已完成成就官职list

    private achievementListRef: Node | null = null;

    private list = []

    async start() {
        this.achievementListRef = find("Canvas/list")
        this.goBack.on(Node.EventType.TOUCH_START, this.goBackHome, this);
        await this.init()
    }

    update(deltaTime: number) {

    }

    async init() {
        // useStore().userStore.userInfo.maxScore
        await this.littleGameAchievement()
        this.handleAchievementList()
    }

    goBackHome() {
        director.loadScene('home')
    }
    

    handleAchievementList() {
        this.list.forEach((item, index) => {
            console.log(item, 111)
            let itemRef = instantiate(this.item);
            const prefab = this.prefabRendering(itemRef, item, index)
            this.achievementListRef.addChild(prefab)
        })
        // 
    }

    prefabRendering(prefab, item, index) {
        prefab.getChildByPath("info/name").getComponent(Label).string = item.title
        prefab.getChildByPath("info/desc").getComponent(Label).string = item.desc
        if (Number(useStore().userStore.userInfo.maxScore) >= Number(item.score)) {
            prefab.getComponent(Sprite).spriteFrame = this.activeGZList[index]
            prefab.getChildByName("status").getComponent(Sprite).spriteFrame = this.statusList[1]
        } else {
            prefab.getComponent(Sprite).spriteFrame = this.defaultGZList[index]
        }
        return prefab
    }

    // 获取成就list
    async littleGameAchievement() {
        await api.game.getByKey({
            key: 'littleGameAchievement'
        }).then((res) => {
            this.list = res.list
        })
    }
}

